window.onload = () => {
  var scale = 1;
  var speed = 1;
  // 获取当前地址栏地址
  var getURL = window.location.href;
  // console.log(getURL)
  var getURL = getURL.replace(/index.html/, '')
  var ns = getURL.indexOf('?')
  // 提取主要链接
  var getURL = getURL.substring(0, ns);

  // 获取元素
  var getPath = document.querySelector(".path");
  var getNum = document.querySelector(".num");
  var getSpeed = document.querySelector(".speed");
  var getBtn = document.querySelector(".btn");
  var getCss = document.querySelector(".css");

  var imgLoad = document.querySelector(".loading");

  getBtn.addEventListener('click', function () {
    start()
  }
  )
  function getQuery() {
    const url = decodeURI(location.search); // 获取url中"?"符后的字串(包括问号)
    let query = {};
    if (url.indexOf("?") != -1) {
      const str = url.substr(1);
      const pairs = str.split("&");
      for (let i = 0; i < pairs.length; i++) {
        const pair = pairs[i].split("=");
        query[pair[0]] = pair[1];
      }
      return query;  // 返回对象
    } else {
      return false
    }
  }

  if (getQuery() != false) {
    let urlPath = getQuery().path;
    let urlNum = getQuery().num;
    let urlSpeed = getQuery().speed;
    getPath.value = urlPath;
    getNum.value = urlNum;
    getSpeed.value = urlSpeed;
    start()
  } else {
    getPath.value = localStorage.getItem("path");
    getNum.value = localStorage.getItem("num");
    getSpeed.value = localStorage.getItem("speed");
  }

  /*开始*/
  function start() {
    imgLoad.style.display="block";
    let path = getPath.value;
    let num = getNum.value;
    speed = getSpeed.value;
    speed = speed ? Number(speed) : 1;
    localStorage.setItem("path", path);
    localStorage.setItem("num", num);
    localStorage.setItem("speed", speed);
    let list = num.split("-");
    loadImages(path, Number(list[0]), Number(list[1]), drawImages);
    changeURLParam(path, num, speed)
  }
  /*修改URL*/
  function changeURLParam(path, num, speed) {
    let url = getURL, resultUrl = '?path=' + path + '&num=' + num + '&speed=' + speed
    history.replaceState(null, null, resultUrl)
  }
  /*绘制序列图片*/
  function drawImages(imgs) {
    let total = imgs.length;
    let w = Math.ceil(imgs[0].naturalWidth * scale);
    let h = Math.ceil(imgs[0].naturalHeight * scale);
    let col = total;
    let row = Math.ceil(total / col);
    // console.log(row,total,col)
    let canvas = document.querySelector(".canvas");
    canvas.width =( w > h ? row : col  )* w;
    canvas.height = ( w > h ? col : row  )* h;
    console.log('cw:'+canvas.width)
    console.log('ch:'+canvas.height)

    let ctx = canvas.getContext("2d");
    ctx.clearRect(0, 0, canvas.width, canvas.height);
    let id = 0;
    for (let i = 0; i < row; i++) {
      for (let j = 0; j < col; j++) {
        if (id < total) {
          ctx.drawImage(imgs[id++],  (w > h ? i : j ) * w, (w > h ? j : i )* h, w, h);
        }
      }
    }
    createStyle(w, h, total, col, speed);
    makeCartoon(w, h, total, canvas, speed);
  }

  /*加载绘制序列图片*/
  function makeCartoon(w, h, total, canvas) {
    let cartoon = document.querySelector(".cartoon");
    
    cartoon.style.width = w + "px";
    cartoon.style.height = h + "px";
    try {
      cartoon.style.backgroundImage = 'url("' + canvas.toDataURL() + '")';
      cartoon.style.animation = "play steps(" + total + ") " + speed + "s infinite";
    }
    catch (e) {
      console.log(e);
      cartoon.innerHTML = "未使用http协议开启，无法预览，但不影响使用";
      cartoon.style.color = "red";
    }
    imgLoad.style.display="none";
  }

  /*生成动画样式*/
  function createStyle(w, h, total, col, speed) {
    // console.log(w, h)
    let XY = w > h ? '-y':'-x';
    // console.log( w > h)
    let style = document.createElement("style");
    let list = [];
    list.push("/* 右键保存上面👆图片再引入 */");
    list.push("@keyframes play{");
    list.push("0%{background-position"+XY+": 0;}");
    list.push("  100%{background-position"+XY+': -' + (w > h ? h:w ) * total + "px;}");
    list.push("}");
    let css = list.join("\n");
    style.innerHTML = css;
    document.body.appendChild(style);
    list.push(".item{");
    list.push(" width:" + w + "px;");
    list.push(" height:" + h + "px;");
    list.push(" background-image: url(\"保存的图片.png\");");
    list.push(" animation: play steps(" + total + ") " + speed + "s infinite;");
    list.push("}");
    getCss.innerHTML = list.join("\n");
  };
  /*加载序列图片*/
  function loadImages(name, start, end, callback) {
    getCss.innerHTML = ''
    var name = getURL + name;
    let progress = 0;
    let total = end - start + 1;
    let imgs = [];
    for (let i = start; i <= end; i++) {
      let zh = end.toString().length;
      let img = new Image();
      img.src = name.replace("*", (i <= 9 ? '0' + i : i));
      CheckImgExists(img.src)
      img.onload = function () {
        if (++progress == total) {
          callback(imgs);
        }
      }
      imgs.push(img);
    }
  }
  // 检测imgSrc是否有效
  function CheckImgExists(imgurl) {
    return new Promise(function (resolve, reject) {
      var ImgObj = new Image(); //判断图片是否存在
      ImgObj.src = imgurl;
      ImgObj.onload = function (res) {
        resolve(res);
      }
      ImgObj.onerror = function (err) {
        getCss.append('图片路径错误' + err.path[0].src + "\n");
        imgLoad.style.display="none";
      }
    })
  }
}